package redisinit

import (
	"cartsrv/cart"
	"context"
	"fmt"
	"strconv"
)

func AddCart(userId, goodsId, goodsNumber int, goodsName string, price float64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"goodsId":     goodsId,
		"goodsName":   goodsName,
		"goodsNumber": goodsNumber,
		"Price":       price,
		"Checked":     1,
	}).Err()
}
func CartList(userId int) (cartLists []cart.CartList, err error) {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, v := range keys {
		goodsInfo := Rdb.HGetAll(context.Background(), v).Val()
		goodsId, _ := strconv.Atoi(goodsInfo["goodsId"])
		goodsNumber, _ := strconv.Atoi(goodsInfo["goodsNumber"])
		Checked, _ := strconv.Atoi(goodsInfo["Checked"])
		goodsName := goodsInfo["goodsName"]
		Price, _ := strconv.ParseFloat(goodsInfo["Price"], 64)
		cartLists = append(cartLists, cart.CartList{
			UserId:      int64(goodsId),
			GoodsName:   goodsName,
			GoodsNumber: int64(goodsNumber),
			Price:       float32(Price),
			Checked:     int64(Checked),
		})
	}
	return
}
